package com.yupi.yuojbackendcommon.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
//@ConfigurationProperties(prefix = "mail")
public class EmailUtil {
    // 邮件服务器的SMTP地址，可选，默认为smtp.<发件人邮箱后缀>
    @Value("${mailConfig.smtpHost}")
    private String host;

    // 邮件服务器的SMTP端口，可选，默认25
    @Value("${mailConfig.smtPort}")
    private int port;

    // 发件人（必须正确，否则发送失败）
    @Value("${mailConfig.from}")
    private String fromEmailAddress;

    // 用户名，默认为发件人邮箱前缀
//    @Value("${mailConfig.user}")
//    private String user;

    // 密码（注意，某些邮箱需要为SMTP服务单独设置授权码)
    @Value("${mailConfig.pass}")
    private String password;

    @Value("${mailConfig.subject}")
    private String subject;

    @Value("${mailConfig.contentPre}")
    private String contentPre;

    @Value("${mailConfig.contentEnd}")
    private String contentEnd;

    private MailAccount getMailCount() {
        MailAccount account = new MailAccount();
        account.setHost(host);
        account.setPort(port);
        account.setAuth(true);
        account.setFrom(fromEmailAddress);
//        account.setUser(user);
        account.setPass(password);
        return account;
    }

    /**
     * 发送普通邮件
     *
     * @param toMail 收件人
     * @param code   标题
     */
    public void sendNormalEmail(String toMail, String code) {
        MailAccount account = getMailCount();
        ArrayList<String> mailList = CollUtil.newArrayList(
                toMail);
        MailUtil.send(account, mailList, subject,
                "<h2> " + contentPre + code + contentEnd + "</h2>", true);
    }

}
